package com.by_man.presenter.module_health_consultant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.repository.IpAddress;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.NetworkDataManager;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;

/**
 * Created by man on 2017-02-23.
 */
public class HealthConsultantFragment extends Fragment {
    private RequestQueue rQueue;
    private ImageLoader imageLoader;
    private ProgressDialog progressDialog;
    private Handler handler;
    private TextView textView;
    private ListView docList;
    private boolean isContinue = false;
    // 存储医生信息的列表
    List<Map<String, Object>> docInfos = new ArrayList<Map<String, Object>>();

    final ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

    private String userid;
    //private String docName;
    private boolean isFull = false;

    @Override   //绑定布局
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_health_consultant, container, false);
        docList = (ListView) view.findViewById(R.id.list_doc);         // 所以医生列表
        textView  = (TextView) view.findViewById(R.id.text_view);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                initView();
            }
        };
        dataInitWait();
        return view;
    }

    private void initView() {

        docList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String urlDocInfo = getResources().getString(R.string.doc_info);
                HashMap<String, String> paramsPost = new HashMap<String, String>();
                if (isFull) {
                    // 获取医生详细信息
                    paramsPost.put("token", UserInfos.token);
                    paramsPost.put("arg",userid);
                    final int position = i;
                    PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Doctor_Infos, paramsPost,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Intent intent = new Intent(getActivity(), DoctorInfosActivity.class);
                                    intent.putExtra("jsonString", response);
                                    intent.putExtra("ischosed", true);
                                    intent.putExtra("name", (String)docInfos.get(position).get("13"));
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent);
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e("HealthConsultantError",volleyError.getMessage(),volleyError);
                                    Toast.makeText(getActivity(), "医生详情获取失败！",Toast.LENGTH_SHORT).show();
                                }
                            });
                    rQueue.add(stringRequest);
                } else {
                    paramsPost.put("token", UserInfos.token);
                    final String id = (String)docInfos.get(i).get("userid");
                    final String name = (String) docInfos.get(i).get("13");
                    paramsPost.put("arg", id);
                    PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Doctor_Infos, paramsPost,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Intent intent = new Intent(getActivity(), DoctorInfosActivity.class);
                                    intent.putExtra("jsonString", response);
                                    intent.putExtra("ischosed", false);
                                    intent.putExtra("name", name);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent);
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e("HealthConsultantError",volleyError.getMessage(),volleyError);
                                    Toast.makeText(getActivity(), "医生详情获取失败！",Toast.LENGTH_SHORT).show();
                                }
                            });
                    rQueue.add(stringRequest);
                }
            }
        });

        JSONArray jsonArray = LocalDataManager.getAllDoctor();
        if (null != jsonArray) {
            try {
                JSONObject isSelect = (JSONObject) jsonArray.get(0);
                if (isSelect.getBoolean("isFull")) {
                    isFull = true;
                    JSONObject infoDoc = (JSONObject) jsonArray.get(1);
                    //13医生姓名；14医生职称；18医生图片
                    final HashMap<String, Object> hashdoc = new HashMap<String, Object>();
                    hashdoc.put("13", infoDoc.getString("value"));
                    hashdoc.put("14", infoDoc.getString("job"));
                    hashdoc.put("18", infoDoc.getString("path"));
                    userid = infoDoc.getString("userid");
                    docInfos.clear();
                    docInfos.add(hashdoc);
                    textView.setText("你的顾问");
                    docList.setAdapter(new ListViewAdapter());
                } else {
                    isFull = false;
                    //没有选择顾问，开始申请医院名称、地址、医生等
                    Map<String, Object> test1 = new HashMap<String, Object>();
                    JSONObject temp1 = (JSONObject) jsonArray.get(1);
                    String users_id = temp1.getString("users_id");
                    for (int j = 1; j < jsonArray.length(); j++) {
                        JSONObject temp2 = (JSONObject) jsonArray.get(j);
                        final String users_id2 = temp2.getString("users_id");
                        if (users_id.equals(users_id2)) {
                            final String list_id = temp2.getString("list_id");
                            final String value = temp2.getString("value");
                            test1.put(list_id, value);
                        } else {
                            test1.put("userid", users_id);
                            docInfos.add(test1);
                            users_id = users_id2;
                            test1 = new HashMap<String, Object>();
                        }
                    }
                    docList.setAdapter(new ListViewAdapter());

                }
            } catch (JSONException je) {
                je.printStackTrace();
            }
        }
    }

    // 多次请求服务器后仍无反应，询问用户是否继续
    public void showRequestAgain() {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("提醒")
                .setMessage("已多次请求服务器，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        NetworkDataManager.DocNum = 3;
                        LocalDataManager.getAllDoctor();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        isContinue = true;
                    }
                }).create();
        alertDialog.show();
    }

    // 如果数据还没有，就开启一个线程不停的检测数据是否存在，如果存在，就刷新页面
    private void dataInitWait() {
        if (null == UserInfos.All_Doctor) {     // 没有数据
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();
            if (NetworkDataManager.DocNum < 1) {  // 多次请求没有结果
                showRequestAgain();               // 询问用户是否继续请求数据
            }

            Thread thread = new Thread() {
                public void run() {
                    while (null == UserInfos.All_Doctor) {  // 阻塞等待数据的初始化
                        if (NetworkDataManager.DocNum < 1) {
                            showRequestAgain();
                        }
                        if (isContinue) break;
                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
            //rQueue = Volley.newRequestQueue(getActivity());
            //imageLoader = new ImageLoader(rQueue,new BitmapCache());
            rQueue = SharedApplication.getrQueue(getActivity().getApplication());
            imageLoader = SharedApplication.getImageLoader(getActivity().getApplication());
        } else {
            initView();
            //rQueue = Volley.newRequestQueue(getActivity());
            //imageLoader = new ImageLoader(rQueue,new BitmapCache());
            rQueue = SharedApplication.getrQueue(getActivity().getApplication());
            imageLoader = SharedApplication.getImageLoader(getActivity().getApplication());
        }
    }

    private class ListViewAdapter extends BaseAdapter {
        @Override
        public int getCount()
        {
            return docInfos.size();
        }

        @Override
        public Object getItem(int position)
        {
            return docInfos.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            if(null == convertView) {
                convertView = View.inflate(getActivity(), R.layout.health_consultant_listview_item, null);
            }

            TextView nameView= (TextView) convertView.findViewById(R.id.docname);
            TextView jobView= (TextView) convertView.findViewById(R.id.job);
            ImageView imageview = (ImageView)convertView.findViewById(R.id.path);
            if(!docInfos.get(position).get("18").equals("null")) {
                String url = IpAddress.Load_Image + docInfos.get(position).get("18");
                //rQueue.add(SharedApplication.imageRequest(url, imageview, getActivity()));
                ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageview,R.drawable.no,R.drawable.no);
                imageLoader.get(url, listener);
            }

            //13医生姓名；14医生职称；18医生图片
            nameView.setText((String) docInfos.get(position).get("13"));
            jobView.setText((String) docInfos.get(position).get("14"));
            return convertView;
        }
    }

    // 不知能否解决内存泄露
    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

}
